package com.cn.wanxi.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFileter implements Filter {
    /**
     * servlet的生命周期？
     * 项目初始化
     * init 只执行一次
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//写定时器,
    }

    /**
     * 过滤器
     * 如果需要过滤，
     * 接口放行？
     * 接受所有访问后台的链接
     * 哪些需要登录才能访问，哪些不需要登录就可以访问?
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        System.out.println("aaaaaaaa");
//        将访问后台的地址链接得到
//        String path=servletRequest.getRealPath("");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        String path = req.getServletPath();
        System.out.println(path);
        //需要在登录成功后设置一个标识，判断是否为当前用户
        if (path.startsWith("/back/")) {
            String loginName = (String) req.getSession().getAttribute("username");
            if (loginName == null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", "noLogin");
                resp.getWriter().println(jsonObject);
            } else {
                filterChain.doFilter(req, resp);
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        //放行
//        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 销毁  也是只执行一次
     */
    @Override
    public void destroy() {

    }
}
